<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Menu_Services_Menu
{
	const EOL = "\n";
	
	public static function validate($data)
	{
		$validator = new Gio_Core_Validator();
		foreach ($data as $index => $value) {
			if (gettype($value) == 'string') {
				$data[$index] = trim($value);
			}
		}
		
		$data['messages']['language'] = $validator->setString($data['language'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'menu_language_notnull',
																)
														);
														
		$data['messages']['name'] = $validator->setString($data['name'])
												->validate(array('notNull')
																, array(
																	'notNull' => 'menu_name_notnull',
																)
														);
		
		$error = false;
		foreach ($data['messages'] as $index => $message) {
			if ($message) {
				$data['messages_error'] = true;
				return $data;
			}
		}										
		$data['messages_error'] = false;
		return $data; 
	}
	
	public static function add($menu, $items = array(), $sourceItem = null)
	{
		$conn = Gio_Db_Connection::getConnection();
		$dao  = new Modules_Menu_Models_Mysql_Menu();
		$dao->setConnection($conn);
		$id   = $dao->add($menu);
		
		if ($id) {
			/**
			 * Add translation relation
			 */
			$json 		 = new Services_JSON();
			$source 	 = (array)$json->decode($sourceItem);
			$translation = array(
								'item_id' 	      => $id,
								'item_class'      => get_parent_class($dao),
								'source_item_id'  => (!isset($source['menu_id']) || $source['menu_id'] == '') ? $id : $source['menu_id'],
								'language'        => $menu['language'],
								'source_language' => (!isset($source['language']) || '' == $source['language']) ? $menu['language'] : $source['language'],
						);
			Modules_Core_Services_Translation::add($translation);
			$string = new Gio_Core_String();
			
			/**
			 * Add menu item
			 */
			if (!empty($items)) {
				foreach ($items as $index => $item) {
					$item = (array)$item;
					$menuItem = array(
						'item_id' 	=> $item['item_id'],
						'label' 	=> $string->escape($item['label']),
						'link' 		=> $string->escape($item['link']),
						'menu_id'	=> $id,
						'left_id'	=> $item['left_id'],
						'right_id'  => $item['right_id'],
						'parent_id' => $item['parent_id'],
					);
					
					Modules_Menu_Services_Item::add($menuItem);
				}
			}
		}
		return $id;
	}
	
	public static function getAllMenus()
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Menu_Models_Mysql_Menu();
		$dao->setConnection($conn);
		return $dao->getAllMenus();
	}
	
	public static function update($menu, $items = array(), $sourceItem = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Menu_Models_Mysql_Menu();
		$dao->setConnection($conn);
		$dao->update($menu);
		
		/**
		 * Update translation relation
		 */
		$json 		 = new Services_JSON();
		$source 	 = self::getSource($menu);
		
		$translation = array(
								'item_id' 	      => $menu['menu_id'],
								'item_class'      => get_parent_class($dao),
								'source_item_id'  => (!isset($source['menu_id']) || $source['menu_id'] == '') ? $menu['menu_id'] : $source['menu_id'],
								'language'        => $menu['language'],
								'source_language' => (!isset($source['language']) || '' == $source['language']) ? null : $source['language'],
		);
		
		$sourceItem 	 = $json->decode($sourceItem);
		if ($sourceItem != null) {
			$translation['source_item_id'] = $sourceItem->id;
			$translation['source_language'] = $sourceItem->language;
		}
		
		if ($source != null) {
			Modules_Core_Services_Translation::update($translation);
		} else {
			Modules_Core_Services_Translation::add($translation);
		}
		
		/**
		 * Delete all menu items
		 */
		Modules_Menu_Services_Item::delete($menu['menu_id']);
		$string = new Gio_Core_String();
		
		/**
		 * Add menu item
		 */
		if (!empty($items)) {
			foreach ($items as $index => $item) {
				$item = (array)$item;
				$menuItem = array(
					'item_id' 	=> $item['item_id'],
					'label' 	=> $string->escape($item['label']),
					'link' 		=> $string->escape($item['link']),
					'menu_id'	=> $menu['menu_id'],
					'left_id'	=> $item['left_id'],
					'right_id'  => $item['right_id'],
					'parent_id' => $item['parent_id'],
				);
				
				Modules_Menu_Services_Item::add($menuItem);
			}
		}
	}
	
	public static function count($condition)
	{
		$conn	= Gio_Db_Connection::getConnection();
		$dao 	= new Modules_Menu_Models_Mysql_Menu();
		$dao->setConnection($conn);
		if (isset($condition['language']) && isset($condition['language'])) {
			$dao->setLang($condition['language']);
		}
		return $dao->count($condition);
	}
	
	public static function delete($menuId)
	{
		$conn	= Gio_Db_Connection::getConnection();
		$dao 	= new Modules_Menu_Models_Mysql_Menu();
		$dao->setConnection($conn);
		
		/**
		 * Delete all menu item
		 */
		Modules_Menu_Services_Item::delete($menuId);
		
		/**
		 * Delete menu translation
		 */
		Modules_Core_Services_Translation::delete($menuId, get_parent_class($dao));
		
		/**
		 * Delete menu
		 */
		return $dao->delete($menuId);
	}
	
	public static function find($start, $limit, $condition = array())
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Menu_Models_Mysql_Menu();
		$dao->setConnection($conn);
		if (isset($condition['language']) && isset($condition['language'])) {
			$dao->setLang($condition['language']);
		}
		return $dao->find($start, $limit, $condition);
	}
	
	public static function getById($id)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Menu_Models_Mysql_Menu();
		$dao->setConnection($conn);
		return $dao->getById($id);
	}
	
	/**
	 * Display select box listing all menus
	 * which haven't been translated from the default language
	 * 
	 * @param $attributes array
	 * @param string $lang
	 * @return string
	 */
	public static function translatableMenu($attributes = array(), $lang = null)
	{
		$limit 				 = isset($attributes['limit']) ? ($attributes['limit'] + 10) : 10;
		$attributes['limit'] = $limit;
		
		$view = Gio_Core_View::getInstance();
		
		$json = new Services_JSON();
		$defaultLang     = (string)Gio_Core_Config_Xml::getConfig('web')->language;
		$lang = (null == $lang) ? $defaultLang : $lang;
		$elementDisabled = (null == $lang || $lang == $defaultLang) ? ' disabled="disabled"' : '';
		
		$attributes['selected'] = isset($attributes['selected']) ? $attributes['selected'] : null;
		$attributes['disabled']  = isset($attributes['disabled']) ? $attributes['disabled'] : null;
		
		$menus 	 = self::getTranslatable($lang, $limit);
		$output 		 = sprintf("<select name='%s' id='%s' viewHelperClass='%s' viewHelperAttributes='%s'%s>", 
								$attributes['name'], 
								$attributes['id'],
								'Modules_Menu_Services_Menu::translatableMenu',
								$json->encodeUnsafe($attributes), 
								$elementDisabled) . self::EOL
						. '<option value=\'{"id": "", "language": ""}\'>---</option>' . self::EOL;
		
		foreach ($menus as $menu) {
			$disabled = (0 == (int)$menu['translatable'] 
							&& ((0 == (int)$attributes['disabled'] && $menu['menu_id'] != (int)$attributes['selected'])
								||
							((int)$attributes['disabled'] == (int)$attributes['selected'])))
						? ' disabled="disabled"' 
						: '';
			$selected = ($disabled == ''
							&& (int)$menu['menu_id'] == (int)$attributes['selected'])
						? ' selected="selected"' 
						: '';
			
			$output  .= sprintf("<option value='%s'%s%s>%s</option>", 
								$json->encodeUnsafe(array('id' => $menu['menu_id'], 'language' => $defaultLang)), 
								$selected,
								$disabled,
								$menu['name']) . self::EOL;
		}
		$output .= '<option value="">' . $view->TRANSLATOR->translator('helper_translatable_menu_more', 'menu') . '</option>';
		$output .= '</select>' . self::EOL;

		$id = $attributes['id'];
		$url = $view->url('core_locale_viewhelper');
		
		$scripts = <<<END
		<script type="text/javascript">
			$(document).ready(function() {
				$('#$id').change(function() {
					if ($(this).val() != '') {
						return;
					}
			
					/**
					 * Load more articles
					 */
					var self   = this;
					var parent = $(self).parent(); 
					$(parent).addClass('g_a_ajax_loading');
					
					$.ajaxq('Core_View_Helper_LanguageSelector', {
						url: '$url',
						type: 'POST',
						data: {
							id: $(self).attr('id'), 
							name: $(self).attr('name'), 
							language: '$lang',
							viewHelperClass: $(self).attr('viewHelperClass'), 
							viewHelperAttributes: $(self).attr('viewHelperAttributes') 
						},
						success: function(response) {
							$(parent).html(response).removeClass('g_a_ajax_loading');
			
							/**
							 * Disable source items element if user select the default language
							 */
							if ('$lang' == '$defaultLang') {
								$(self).attr('disabled', 'disabled').find('option:selected').removeAttr('selected');
							} else {
								$(self).removeAttr('disabled');
							}
						}
					});
				});
			});
		</script>
END;
		
		return $output . $scripts;
	}
	
	public static function getTranslatable($lang, $count)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Menu_Models_Mysql_Menu();
		$dao->setConnection($conn);
		return $dao->getTranslatable($lang, $count);
	}
	
	public static function getSource($menu)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$dao = new Modules_Menu_Models_Mysql_Menu();
		$dao->setConnection($conn);
		return $dao->getSource($menu);
	}
}